package mysql;

import java.sql.*;
import java.util.concurrent.*;

/**
 * @author 宋鑫宇
 * @version 1.0
 * 使用PreparedStatement 来防止sql注入
 */
public class JDBC_04 {
    public static void main(String[] args) throws Exception {

        //注册驱动,jdk5之后可以不用写这行
        Class.forName("com.mysql.jdbc.Driver");
        //2.获取数据库连接
        String url = "jdbc:mysql://127.0.0.1:3306/db1?useServerPrepStmts=true";
        String username = "root";
        String password = "root";
        Connection coon = DriverManager.getConnection(url, username, password);
        //3.定义sql语句
        String sql = "select * from stu where name = ? and stu_class = ?;";
        //4.获取执行sql的对象
        PreparedStatement pre = coon.prepareStatement(sql);
        //设置 ? 的值
        pre.setString(1,"tom");
        pre.setInt(2,2);
        //5.执行sql,返回ResultSet对象
        ResultSet rs = pre.executeQuery();
        //6.处理结果
        if (rs.next()){
            System.out.println("成功");
        }else {
            System.out.println("失败");
        }

        //7.释放资源
        coon.close();
        pre.close();
        rs.close();
    }
}
